<template>
  <div class="container">
    <div class="title">
      <label>标题: </label>
      <div class="input">
        <el-input
            maxlength="100"
            type="textarea"
            autosize
            placeholder="在此输入文章标题"
            v-model="articleInfo.title">
        </el-input>
      </div>
      <div class="tip">{{ articleInfo.title.length }}/100</div>
    </div>
    <div class="category">
      <label>分类: </label>
      <div class="select">
        <el-select v-model="articleInfo.categoryId" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.key"
              :label="item.value"
              :value="item.key">
          </el-option>
        </el-select>
      </div>

    </div>
    <div class="button-group">
      <el-button type="primary" @click="dialogFormVisible = true">文件上传模式</el-button>
      <el-button type="danger" disabled >在线编辑模式</el-button>
    </div>



    <!--上传对话框-->
    <el-dialog title="️🧡💛💚💙💜上传文章❤️🧡💛💚💙💜" :visible.sync="dialogFormVisible">
      <el-form :model="articleInfo">
        <el-form-item label="文章标题🌠⭐" :label-width="formLabelWidth">
          <el-input v-model="articleInfo.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" :label-width="formLabelWidth">
          <el-select v-model="articleInfo.categoryId" placeholder="请选择分类">
            <el-option v-for="item in options"
                       :key="item.key"
                       :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-upload
              class="upload-demo"
              :headers="{ 'Content-Type': 'multipart/form-data'}"
              action="none"
              :limit="1"
              :on-change="handleChange"
              :file-list="fileList"
              :auto-upload="false"
              :on-exceed="handleExceed"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传md文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getAllCategoryApi,uploadApi} from '@/api/article'
export default {
  name: "",
  data() {
    return {
      // 文章分类选项
      options: [
        {
          key: null,
          value: ''
        }
      ],
      // 对话框可见性
      dialogFormVisible: false,
      // 对话框中Label的宽度
      formLabelWidth: '120px',
      // 提交的保存文章信息
      articleInfo: {
        title: '',
        categoryId: null,
      },
      // 准备提交的
      formData: {},

      fileList: []
    }
  },
  methods: {
    // 查询全部分类
    selectAllCategory(){
      getAllCategoryApi().then((res) => {
         this.options = res.data;
      })
    },
    // 上传文件-----重要,为了拿到 file.raw
    handleChange(file) {
      // 这两行代码比较重要---核心代码
      this.formData = new FormData();
      // file 我们后端需要的参数名字,看你们需求
      this.formData.append("file", file.raw);
    },
    // 上传超出数量处理
    handleExceed(files, fileList) {
      this.$message.warning(`一次只能上传一个md文件哦! 你当前已准备了 ${ fileList.length} 个文件`);
    },
    // 文件移除前的确认提示
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 文件移除后的处理方式
    handleRemove(){
      // 关键：文件被移除要从这个new 的 FormData对象中删除
      this.formData.delete("file");
    },
    // 提交上传数据
    submitUpload(){
      // 往FormData对象中添加其他参数，文件参数已在点击上传时添加进来了
      this.formData.append("title", this.articleInfo.title);
      this.formData.append("categoryId",this.articleInfo.categoryId)

      // 判断，如果FormData对象中没有了file文件对象，那么就提示，否则开始上传
      if (this.formData.get("file") == null){
        this.$message({
          showClose: true,
          message: '请添加要上传的文件！',
          type: 'warning'
        });
      }else {
        // 开始上传
        uploadApi(this.formData).then(res => {
          if (res.code === 1) {
            this.$message({
              message: '恭喜，您已成功上传一篇文章！',
              type: 'success'
            });
            // 对话框关闭
            this.dialogFormVisible = false
          }else {
            this.$message.error('糟糕，上传失败了');
          }
          // 无论是否上传成功，都重新实例化FormData对象
          this.formData = new FormData();
          // 待上传的文件列表清空，这样不会显示
          this.fileList = []
        })
      }

    }
  },
  created() {
    this.selectAllCategory();
  }
}
</script>

<style scoped lang="scss">

.container {
  width: 1200px;
  margin: 30px auto;
  background-color: white;
  // 标题区域
  .title {
    width: 100%;
    font-size: 25px;
    label {
      margin: 30px;
      float: left;
      display: block;
    }
    .input {
      float: left;
      ::v-deep .el-textarea {
        font-size: 20px;
        width: 600px;
        margin-top: 30px;
      }
    }
    .tip {
      float: left;
      margin: 30px;
      font-size: 15px;
    }
  }
  .title::after {
    display: block;
    content: '';
    clear: both;
  }

  // 分类区域
  .category {
    width: 100%;
    font-size: 25px;
    margin-bottom: 30px;
    label {
      display: block;
      float: left;
      margin:0 30px;
    }
    .select {
      float: left;
    }
  }
  .category::after {
    display: block;
    content: '';
    clear: both;
  }


  // 按钮组
  .button-group {
    // 文件上传方式按钮
    ::v-deep .el-button--primary {
      background-color: #e37272;
      border: none;
      font-size: 15px;
      letter-spacing: 2px
    }
    // 在线编辑按钮
    ::v-deep .el-button--danger {
      background-color: #4ac160;
      border: none;
      font-size: 15px;
      letter-spacing: 2px
    }
  }
}
</style>